package com.fjk.gateway.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class GlobalFilterConfig implements GlobalFilter, Ordered {
    @Autowired
    private RedisTemplate redisTemplate;

    private static final String HEADER_NAME = "Acess-Token";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //获取请求地址
        String url = request.getURI().getPath();
        //获取token
        String token = request.getHeaders().getFirst(HEADER_NAME);

        //判断是否为不需要验证接口
        if (this.shouldNotFilter(url)){
            return chain.filter(exchange);
        }

        //验证redis中是否存在tokne
        if (StringUtils.isEmpty(token) || !redisTemplate.hasKey(token)){
            return unAuthorized(exchange);
        };
        return chain.filter(exchange);
    }

    private Mono<Void> unAuthorized(ServerWebExchange exchange) {
        //设置错误响应码
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        //设置返回的信息为json
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //自定义错误信息
        String errorMsg = "{ \"error\":\"用户未登录或登录超时,请重新登录\"}";
        //写入响应体
        return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(errorMsg.getBytes())));
    }

    private boolean shouldNotFilter(String url) {
        if ("/auth/login".equals(url)) return true;
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
